package com.wxb.plugin.action;

import com.intellij.ide.projectView.impl.nodes.ClassTreeNode;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.ide.projectView.impl.nodes.PsiFileNode;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.wxb.plugin.core.gen.InterfaceApiGen2;
import com.wxb.plugin.core.gen.StringUtil;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static com.wxb.plugin.core.gen.InterfaceApiGen2.docxPrefix;

public class SwaggerAction extends AnAction {


    public SwaggerAction() {
        super("Swagger Helper");
    }



    public static String actionChooseForPath(AnActionEvent event) {
        Project project = event.getProject();
        FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
        descriptor.setDescription("请选择接口文档的保存目录");
        descriptor.setTitle("选择文档保存路径");
        VirtualFile[] virtualFiles = FileChooser.chooseFiles(descriptor, project, null);

        for (VirtualFile virtualFile : virtualFiles) {
            return virtualFile.getCanonicalPath();
        }
        return project.getBasePath();
    }

    public static String actionChooseForFileType() {
        // 定义对话框的选项
        String[] options = {"Word文档", "Markdown"};
        String title = "选择文档类型";
        String message = "请选择您想要的文档类型";

        // 显示对话框并等待用户选择
        int choice = Messages.showDialog(message, title, options, 0, Messages.getQuestionIcon());

        // 根据用户的选择执行不同的逻辑
        if (choice == 0) {
            // 用户选择了DOC
            System.out.println("用户选择了：DOC");
        } else if (choice == 1) {
            // 用户选择了MD
            System.out.println("用户选择了：MD");
        }
        return choice == 0 ? "word" : "md";
    }

    public static void getPsiClass(Set<PsiClass> psiClassSet, PsiElement... children) {
        for (PsiElement child : children) {
            if (child instanceof PsiJavaFile javaFile) {
                psiClassSet.addAll(List.of(javaFile.getClasses()));
            } else if (child instanceof PsiDirectory) {
                PsiElement[] elements = child.getChildren();
                getPsiClass(psiClassSet, elements);
            } else if (child instanceof PsiClass psiClass) {
                psiClassSet.add(psiClass);
            }
        }
    }

    public Set<PsiClass> getScanDir(AnActionEvent event) {
        Set<PsiClass> psiClassSet = new LinkedHashSet<>();
        Navigatable[] navigatableList = event.getData(CommonDataKeys.NAVIGATABLE_ARRAY);
        if (navigatableList != null) {
            // 从项目视图中的目录节点展示中获取class
            for (Navigatable navigatable : navigatableList) {
                if (navigatable instanceof PsiFileNode fileNode) {
                    PsiElement[] children = fileNode.getValue().getChildren();
                    getPsiClass(psiClassSet, children);
                } else if (navigatable instanceof ClassTreeNode treeNode) {
                    psiClassSet.add(treeNode.getPsiClass());
                } else if (navigatable instanceof PsiDirectoryNode directory) {
                    getPsiClass(psiClassSet, directory.getValue().getChildren());
                }
            }
        } else {
            // 如果用户没有选择指定目录，则从根目录开始
            Project project = event.getProject();
            if (project != null && project.getBasePath() != null) {
                VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(project.getBasePath());
                if (fileByPath != null) {
                    PsiDirectory directory = PsiManager.getInstance(project).findDirectory(fileByPath);
                    getPsiClass(psiClassSet, directory);
                }
            }
        }
        return psiClassSet;
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) {
            return;
        }

        // 获取文件存储目录
        String outPutPath = actionChooseForPath(event);
        // 获取文件类型
        String fileType = actionChooseForFileType();
        Config config = new Config(outPutPath + "/",
                fileType,
                StringUtil.isNotBlank(project.getName()) ? project.getName() : InterfaceApiGen2.docxPrefix);
        // 扫描获取class
        Set<PsiClass> psiClasses = getScanDir(event);
        String s = InterfaceApiGen2.genFile(psiClasses, config);


        Messages.showMessageDialog(project, "路径:\n" + s, "文档生成成功", Messages.getInformationIcon());
    }

//    public static void main(String[] args) {
//        ExternalJarLoadClassLoader classLoader = new ExternalJarLoadClassLoader(SwaggerAction.class.getClassLoader(),
//                "fileGen.jar");
//        try {
//            Class<?> aClass = classLoader.loadClass("com.wxb.core.file.api.gen.InterfaceApiGen");
//            Method run = aClass.getMethod("run",String.class,String.class);
//            run.invoke(null, "src/main/java/test","src");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public void test(AnActionEvent event) {
        Project project = event.getData(PlatformDataKeys.PROJECT);
        String txt = Messages.showInputDialog(project, "What is your name?", "Input your name", Messages.getQuestionIcon());
        Messages.showMessageDialog(project, "Hello, " + txt + "!\n I am glad to see you.", "Information", Messages.getInformationIcon());
    }

    @Override
    public boolean isDumbAware() {
        return super.isDumbAware();
    }
}
